//import * as THREE from "three";
import * as THREE from "../threejs/three.module.js";
import { OrbitControls } from '../threejs/jsm/controls/OrbitControls.js';
import {pointsToVertices,showVertices} from "./coordinate.js";

// 索引数组，定义每个面由哪些顶点构成 (每个面由两个三角形组成)
const indicesCube = [
    0, 1, 2, 0, 2, 3,   // 前面
    4, 5, 6, 4, 6, 7,   // 后面
    0, 1, 5, 0, 5, 4,   // 底面
    3, 2, 6, 3, 6, 7,   // 顶面
    0, 3, 7, 0, 7, 4,   // 左面
    1, 2, 6, 1, 6, 5    // 右面
];
const  CUBE_TYPES   = ',Z,L,LQ,'  //长方体类别
const  CUBE_TYPE_Z  = 'Z'  //立柱
const  CUBE_TYPE_L  = 'L'  //梁
const  CUBE_TYPE_LQ = 'LQ' //梁墙

// 创建 Raycaster 和鼠标 Vector2
const cRaycaster = new THREE.Raycaster();
const cMouse = new THREE.Vector2();
const cRenderer = new THREE.WebGLRenderer();
var hScene = null
var hCamera = null

function fnRender() {
    if(hScene==null || typeof(hScene)=='undefined'){
        return
    }
    if(hCamera==null || typeof(hCamera)=='undefined'){
        return
    }
    ThreeDim.renderer.render(hScene,hCamera);
    requestAnimationFrame(fnRender);
}
export const ThreeDim = {
    scene : null,
    camera: null,
    renderer:cRenderer,
    cubes: [],
    raycaster :cRaycaster,
    mouse : cMouse,
    drawCubeByPlanes:function(optCubes){
        var lstCube = new Array()
        if(this.scene==null || typeof(this.scene)=='undefined'){
            return lstCube
        }
        if(optCubes==null || typeof(optCubes)=='undefined'){
            return lstCube
        }
        if(!(optCubes instanceof Array)){
            return lstCube
        }
        var iSize = optCubes.length
        var iIdx
        var optCube
        var type,points,indices,opt
        var cube
        for(iIdx=0;iIdx<iSize;iIdx++){
            optCube = optCubes[iIdx];
            if(optCube==null || typeof(optCube)=='undefined' ){
                continue
            }
            type = optCube.type
            points = optCube.points
            indices = optCube.indices
            opt = optCube.opt
            if(indices==null || typeof(indices)=='undefined' ){
                indices = indicesCube
            }
            if(points==null || typeof(points)=='undefined' || !(points instanceof Array)){
                continue
            }
            cube = this.drawCubeByPlane(type,points,indices,opt)
            if(null==cube || typeof(cube)=='undefined' ){
                continue
            }
            lstCube.push(cube)
        }
        return lstCube
    },
    drawCubeByPlane:function(type,points,indices,opt){
        this.init()
        if(this.scene==null ||typeof(this.scene)=='undefined'){
            return null
        }
        if(type==null || typeof(type)=='undefined'){
            type = CUBE_TYPE_Z
        }
    
        var sType = ','+type.toUpperCase()+','
        if(CUBE_TYPES.indexOf(sType)<0){
            type = CUBE_TYPE_Z
        }
        var vertices = pointsToVertices(points,type)
        showVertices(vertices,type)
    
        var geometry = new THREE.BufferGeometry();
        geometry.setAttribute("position", new THREE.BufferAttribute(vertices, 3));

        
        if(indices==null || typeof(indices)=='undefined'){
            indices = indicesCube
        }

        if(indices!=null && typeof(indices)!='undefined'){
            geometry.setIndex(indices);
        }
        var color = 0xdd3c3c
        if(type==CUBE_TYPE_Z){ //立柱
            color = 0xdd3c3c
        }else if(type== CUBE_TYPE_L){ //梁
            color = 0xe1e135
        }else if(type==CUBE_TYPE_LQ){  //梁墙
            color = 0x4d4dff
        }
        geometry.computeVertexNormals(); // 计算法线，确保光照正常
        var material = new THREE.MeshStandardMaterial({
            color: color,
            side: THREE.DoubleSide,
        });
        var cube = new THREE.Mesh(geometry, material);
        cube.castShadow = true;
        cube.userData = {points:points,opt:opt};
        this.scene.add(cube);
        return cube;
    },
    //初始化三维场景
    init:function(){
        if(null!=this.scene && typeof(this.scene)!='undefined'){
            return
        }

        // this.raycaster = new THREE.Raycaster();
        // this.mouse = new THREE.Vector2();
        // this.scene = new THREE.Scene();

        this.raycaster = cRaycaster;
        this.mouse = cMouse;

        this.scene = new THREE.Scene();
        this.scene.background = new THREE.Color(0x000000)

        this.camera = new THREE.PerspectiveCamera(90, window.innerWidth / window.innerHeight, 0.1, 10000);
        this.camera.position.x = 0;
        this.camera.position.y = -100;
        this.camera.position.z += 800;

        hScene = this.scene
        hCamera = this.camera

        // 创建渲染器
        this.renderer = cRenderer
        //this.renderer = new THREE.WebGLRenderer();
        this.renderer.setSize(window.innerWidth, 800);
        // 渲染器能够渲染阴影效果
        this.renderer.shadowMap.enabled = true;
        document.body.appendChild(this.renderer.domElement);

        // 添加网格辅助器
        const gridHelper = new THREE.GridHelper(5000, 50); // 创建一个200单位的网格，细分为50个方格
        gridHelper.rotation.x = 0.5 * Math.PI
        this.scene.add(gridHelper);

        // 方向光
        const directionalLight = new THREE.DirectionalLight(0xFFFFFF, 1);
        directionalLight.position.set(10, 10, 10);

        directionalLight.shadow.mapSize.width = 1024  // default
        directionalLight.shadow.mapSize.height = 1024  // default
        directionalLight.shadow.camera.near = 0.05  // default
        directionalLight.shadow.camera.far = 500  // default
        //将范围调大
        directionalLight.shadow.camera.top = 20 /// 这个是生效的属性
        directionalLight.shadow.camera.right = 20
        directionalLight.shadow.camera.left = -20
        directionalLight.shadow.camera.bottom = -20
        directionalLight.castShadow = true;
        this.scene.add(directionalLight);

        // 环境光
        const ambientLight = new THREE.AmbientLight(0xffffff, 2);
        this.scene.add(ambientLight);

        // 添加鼠标控制
        const controls = new OrbitControls(this.camera, this.renderer.domElement);
        // controls.enableDamping = true; // 使得相机移动更加平滑
        controls.dampingFactor = 0.05; // 阻尼效果

        // 添加 XYZ 坐标轴 (红: X, 绿: Y, 蓝: Z)
        const axesHelper = new THREE.AxesHelper(16);  // 参数表示轴的长度
        this.scene.add(axesHelper);

        // 添加箭头
        const arrowSize = 0.1;  // 箭头大小
        const arrowHeadLength = 0.15; // 箭头头部长度
        const arrowHeadWidth = 0.1;  // 箭头头部宽度

        // X 轴箭头 (红色)
        const xArrow = new THREE.ArrowHelper(
            new THREE.Vector3(1, 0, 0),   // 方向 (沿 X 轴)
            new THREE.Vector3(4, 0, 0),   // 起点 (X 轴末端)
            arrowSize,                    // 箭头长度
            0xff0000,                     // 红色
            arrowHeadLength,              // 箭头头部长度
            arrowHeadWidth                // 箭头头部宽度
        );
        this.scene.add(xArrow);

        // Y 轴箭头 (绿色)
        const yArrow = new THREE.ArrowHelper(
            new THREE.Vector3(0, 1, 0),   // 方向 (沿 Y 轴)
            new THREE.Vector3(0, 4, 0),   // 起点 (Y 轴末端)
            arrowSize,                    // 箭头长度
            0x00ff00,                     // 绿色
            arrowHeadLength,              // 箭头头部长度
            arrowHeadWidth                // 箭头头部宽度
        );
        this.scene.add(yArrow);

        // Z 轴箭头 (蓝色)
        const zArrow = new THREE.ArrowHelper(
            new THREE.Vector3(0, 0, 1),   // 方向 (沿 Z 轴)
            new THREE.Vector3(0, 0, 4),   // 起点 (Z 轴末端)
            arrowSize,                    // 箭头长度
            0x0000ff,                     // 蓝色
            arrowHeadLength,              // 箭头头部长度
            arrowHeadWidth                // 箭头头部宽度
        );
        this.scene.add(zArrow);
        fnRender()
        
        // 监听鼠标移动事件
        //window.addEventListener('mousemove', this.onMouseMove, false);
        //window.addEventListener('click', this.onMouseClick, false);
    },
    render:function() {
        cRenderer.render(hScene,hCamera);
        requestAnimationFrame(cRenderer);
    },
    onMouseMove:function(event){
        // 将鼠标位置归一化到 -1 到 1 之间（适用于 Three.js）
        cMouse.x = (event.clientX / window.innerWidth) * 2 - 1;
        cMouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

        // 通过 Raycaster 投射一条射线
        cRaycaster.setFromCamera(cMouse, hCamera);

        // 检查与哪些对象相交
        const intersects = cRaycaster.intersectObjects(hCamera.children);
    },
    // 监听鼠标点击事件
    onMouseClick:function(event){
        // 将鼠标坐标转换为标准化设备坐标 (NDC)
        cMouse.x = (event.clientX / window.innerWidth) * 2 - 1;
        cMouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

        // 通过 Raycaster 检测物体
        cRaycaster.setFromCamera(cMouse, hCamera);
        var intersects = cRaycaster.intersectObjects(hCamera.children);

        console.log('onMouseClick ',cMouse ,intersects)
        if(intersects==null || typeof(intersects)=='undefined' || intersects.length<1){
            return
        }
        var element = intersects[0]
        var userData = element.object.userData
        if(userData==null || typeof(userData)=='undefined'){
            return
        }
        alert('userData='+userData)
    }
    
}